package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
public class UserInfoService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    public boolean saveInfo(Map<String, String> param, String token) {
        //我们要通过token获取user
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }
        //保存用户详细数据
        UserInfo userInfo = UserInfo.builder().birthday(param.get("birthday")).city(param.get("city"))
                .nickName(param.get("nickname")).userId(user.getId())
                .sex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN).build();

        return userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveLogo(MultipartFile headPhoto, String token) {
        //我们要通过token获取user
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }
        try {
            boolean b = faceEngineService.checkIsPortrait(headPhoto.getBytes());
            if (!b) {
                return false;
            }
        } catch (Exception e) {
            log.error("人脸识别失败", e);
            return false;
        }
        //上传到oss
        PicUploadResult upload = picUploadService.upload(headPhoto);
        boolean empty = StringUtils.isEmpty(upload.getName());
        if(empty){
            return false;
        }
        //update头像到userInfo里
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(upload.getName());
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, user.getId());

        return userInfoMapper.update(userInfo, queryWrapper)==1;


    }
}
